package com.lambda.demo.stream;

import com.lambda.demo.models.Author;
import com.lambda.demo.models.AuthorsData;
import com.lambda.demo.models.Book;

import java.util.AbstractMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class Demo {
  public static void main(String[] args) {
    //找出年龄小于100岁的，拥有评分<6的作家的作品
    System.out.println("====传统方式输出结果====");
    for (Author a : AuthorsData.getAuthors()) {
      if (a.getAge() < 100) {
        for (Book b : a.getBooks()) {
          if (b.getScore() < 6) {
            System.out.println("作品评分小于6分的作品《" + b.getName() + "》,作家：" + a.getName() + "作品分数:" + b.getScore() + "分");
          }
        }
      }
    }

    //上面代码用stream如何改写
    System.out.println("====匿名内部类输出结果====");
    AuthorsData.getAuthors().stream()
      .filter(new Predicate<Author>() {
        @Override
        public boolean test(Author a) {
          return a.getAge() < 100;
        }
      })
      .flatMap(new Function<Author, Stream<? extends AbstractMap.SimpleEntry<String, Book>>>() {
                 @Override
                 public Stream<? extends AbstractMap.SimpleEntry<String, Book>> apply(Author a) {
                   return a.getBooks().stream()
                     .filter(b -> b.getScore() < 6)
                     .map(new Function<Book, AbstractMap.SimpleEntry<String, Book>>() {
                       @Override
                       public AbstractMap.SimpleEntry<String, Book> apply(Book b) {
                         return new AbstractMap.SimpleEntry<>(a.getName(), b);
                       }
                     });
                 }
               }
      ).forEach(new Consumer<AbstractMap.SimpleEntry<String, Book>>() {
        @Override
        public void accept(AbstractMap.SimpleEntry<String, Book> e) {
          System.out.println("作品评分小于6分的作品《" + e.getValue().getName() + "》,作家：" + e.getKey() + "作品分数:" + e.getValue().getScore() + "分");
        }
      });


    //上面代码用stream如何改写
    System.out.println("====lambda输出结果====");
    AuthorsData.getAuthors().stream()
      .filter(a -> a.getAge() < 100)
      .flatMap(a -> a.getBooks().stream()
        .filter(b -> b.getScore() < 6)
        .map(b -> new AbstractMap.SimpleEntry<>(a.getName(),b))
      ).forEach(e -> System.out.println("作品评分小于6分的作品《" + e.getValue().getName() + "》,作家：" + e.getKey() + "作品分数:" + e.getValue().getScore() + "分"));
  }
}
